<template>
  <div class="chat-container">
    <!-- 头部标语 -->
    <h1 class="title">小朋友，有什么问题想问我吗？</h1>

    <!-- 显示聊天内容 -->
    <div class="chat-box" ref="chatBox">
      <div class="message" v-for="(msg, index) in messages" :key="index">
        <div :class="msg.isUser ? 'user-message' : 'ai-message'">
          <p>{{ msg.text }}</p>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <input
        v-model="userQuestion" 
        type="text"
        placeholder="请输入你的问题..."
        class="chat-input"
        @keyup.enter="askQuestion" 
        autofocus 
      />
      <button @click="askQuestion" class="send-button">发送</button>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-area">
      <img src="/static/loading.gif" alt="加载中..." class="loading-img" />
      <p>AI正在思考中，请稍候...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-area">
      <p>{{ error }}</p>
      <button @click="resetChat" class="reset-button">重新开始</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userQuestion: "",
      messages: [],
      isLoading: false,
      error: "",
    };
  },
  mounted() {
    // 页面加载时自动发送一条默认的问候消息
    this.sendGreeting();
  },
  methods: {
    // 发送默认的问候消息
    sendGreeting() {
      this.messages.push({ text: "你好！我能帮你什么？", isUser: false });
    },

    async askQuestion() {
      // 确保输入不为空
      if (!this.userQuestion.trim()) {
        this.error = "亲爱的孩子，别忘了输入问题哦！";
        return;
      }
	  console.log("User question:", this.userQuestion);

      // 添加用户提问到消息列表
      this.messages.push({ text: this.userQuestion, isUser: true });

      // 清空输入框并设置加载状态
      this.userQuestion = "";
      this.isLoading = true;
      this.error = "";

      // 调用API获取AI的回答
      try {
        const response = await this.fetchAnswer(this.userQuestion);
        this.messages.push({ text: response.answer, isUser: false });
        this.isLoading = false;

        // 页面滚动到最新消息
        this.$nextTick(() => {
          const chatBox = this.$refs.chatBox;
          chatBox.scrollTop = chatBox.scrollHeight;
        });
      } catch (error) {
        this.error = error || "出现问题，请稍后再试。";
        this.isLoading = false;
      }
    },

    async fetchAnswer(question) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `http://localhost:80/system/user/recommend?keyword=${question}`,
          method: 'GET',
          success: (res) => {
            if (res.data) {
              resolve(res.data); // 返回请求的响应数据
            } else {
              reject('未找到数据');
            }
          },
          fail: (error) => {
            reject('请求失败，请稍后重试');
          },
        });
      });
    },

    resetChat() {
      this.userQuestion = "";
      this.messages = [];
      this.error = "";
      this.isLoading = false;
    },
  },
};
</script>

<style scoped>
.chat-container {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  background-color: #e3f2fd; /* 蓝色背景 */
  border-radius: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  font-family: 'Comic Sans MS', cursive, sans-serif;
}

.title {
  text-align: center;
  font-size: 32px;
  color: #1e88e5; /* 深蓝色标题 */
  margin-bottom: 20px;
  animation: bounce 1s infinite alternate;
}

.chat-box {
  height: 300px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #ffffff; /* 白色背景 */
  border-radius: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message {
  margin: 10px 0;
}

.user-message {
  text-align: right;
  background-color: #bbdefb; /* 浅蓝色用户消息 */
  padding: 12px;
  border-radius: 15px;
  display: inline-block;
  max-width: 75%;
}

.ai-message {
  text-align: left;
  background-color: #c8e6c9; /* 浅绿色AI消息 */
  padding: 12px;
  border-radius: 15px;
  display: inline-block;
  max-width: 75%;
}

.chat-input {
  width: 80%;
  height: 50px;
  padding: 10px;
  font-size: 18px;
  border-radius: 10px;
  border: 2px solid #1e88e5; /* 深蓝色边框 */
  margin-bottom: 10px;
  background-color: #ffffff; /* 白色背景 */
  outline: none;
}

.chat-input:focus {
  border-color: #1565c0; /* 更深的蓝色边框 */
}

.send-button {
  background-color: #1e88e5; /* 深蓝色按钮 */
  color: white;
  padding: 12px 20px;
  font-size: 18px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.send-button:hover {
  background-color: #1565c0; /* 更深的蓝色悬停效果 */
}

.loading-area {
  text-align: center;
  margin-top: 20px;
}

.loading-img {
  width: 50px;
}

.error-area {
  text-align: center;
  color: red;
  font-size: 16px;
  margin-top: 20px;
}

.reset-button {
  background-color: #1e88e5; /* 深蓝色重置按钮 */
  color: white;
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.reset-button:hover {
  background-color: #1565c0; /* 更深的蓝色悬停效果 */
}

@keyframes bounce {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-10px);
  }
}
</style>
